package org.msn.mapper.database.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.msn.mapper.UserMapper;
import org.msn.mapper.database.CreateDatabaseLink;
import org.msn.mapper.database.Repository;

import java.io.Reader;
import java.util.Map;

@Slf4j
public class MySQLRepositoryImpl extends CreateDatabaseLink<Object> implements Repository {
    private volatile SqlSession session = null;
    private volatile UserMapper userMapper = null;

    public MySQLRepositoryImpl(String type, Map<String, Object> info) {
        super(type, info);
    }

    @Override
    protected Object createDatabaseLink(Map<String, Object> info) {
        try {
            String resource = info.get("resource").toString();
            Reader reader = Resources.getResourceAsReader(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            this.session = sqlSessionFactory.openSession();
            userMapper = session.getMapper(UserMapper.class);
        } catch (Exception e) {

        }

        return this;
    }

    @Override
    public Object getSession() {
        return session;
    }
}
